package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 短信发送工具类
 */
public class SMSUtils {
    private static String accessKeyId;
    private static String accessKeySecret;
    private static String signName;
    private static String templateCode;
    private static Client client;

    static {
        Yaml yaml = new Yaml();
        InputStream in = SMSUtils.class.getClassLoader().getResourceAsStream("application.yml");
        Map load = yaml.load(in);
        //读取配置文件中的配置
        SMSUtils.accessKeyId = (String) load.get("accessKeyId");
        SMSUtils.accessKeySecret = (String) load.get("accessKeySecret");
        SMSUtils.signName = (String) load.get("signName");
        SMSUtils.templateCode = (String) load.get("templateCode");
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(SMSUtils.accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(SMSUtils.accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            SMSUtils.client = new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static boolean sendMessage(String phoneNumbers, String param) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(SMSUtils.signName)
                .setTemplateCode(SMSUtils.templateCode)
                .setPhoneNumbers(phoneNumbers)
                .setTemplateParam("{\"code\":\"" + param + "\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            //发送短信api请求
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println("短信发送返回：" + sendSmsResponse.getBody().getMessage());
            System.out.println("短信发送返回：" + JSON.toJSONString(sendSmsResponse.getBody()));
            System.out.println("短信验证码为:" + param);
            if (sendSmsResponse.getBody().getMessage().contains("OK")) {
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;

    }


//    public static void main(String[] args) {
//        Integer integer = 123457;
//
//        SMSUtils.sendMessage("18318974087", Integer.toString(integer));
//    }

}
